<?

if (empty($_SERVER['DOCUMENT_ROOT'])) {
	$_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/geographs.org/httpdocs/";
}

include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

if (false) {
	init_session();

	if (empty($_SESSION['user_id'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
		exit;
	}
}

include($_SERVER['DOCUMENT_ROOT'].'/portals/filter.libs.php');

require $_SERVER['DOCUMENT_ROOT'].'/geograph/Carrot2.class.php';

$id = intval(@$_GET['id']);
if ($id) {
	////
} else {

	//auto!




	$sql = "SELECT portal_id,linear_start_id FROM `portal` WHERE status_id = 1 AND last_grouped < DATE_SUB(NOW(),INTERVAL 7 DAY) ORDER BY portal_id DESC LIMIT 1"; //most recent is likly to be most urgent :)

	$portals = getAssoc($sql);

	foreach ($portals as $id => $gid) {
	
		$images = count_active($id);
	
		print "STARTING portal#$id with $images images<BR>\n";
		
		
		$count = 0;
		if ($images > 10 && $images < 10000) {
		
			$images = getAll("SELECT gridimage_id,title,comment,imageclass FROM p2.gridimage{$id}_bi_view");
				
				
		
			queryExecute("DELETE FROM gridimage_group WHERE portal_id = $id");
			
			
			
			$carrot = Carrot2::createDefault();



			foreach ($images as $idx => $row) {
				$photo = $obj->photo;

				$carrot->addDocument(
					(string)$row['gridimage_id'],
					utf8_encode(htmlentities($row['title'])),
					utf8_encode(htmlentities($row['comment']." ".$row['imageclass'])) #." ".$row['realname']
				);
			}
			if (!empty($_GET['debug'])) {
				print "<hr><pre>";
				print_r($carrot);
				print "</pre>";
			}

			$c = $carrot->clusterQuery();

			function cmp(&$a, &$b)
			{
			    if ($a->score == $b->score) {
				return 0;
			    }
			    return ($a->score > $b->score) ? -1 : 1;
			}
			if (!empty($_GET['debug'])) {
				print "<hr><pre>";
				print_r($c);
				print "</pre>";
			}
			if (!empty($c) && count($c) > 1) {
				usort($c, "cmp");
				$num = 1;
				$done = array();
				foreach ($c as $cluster) {

					foreach ($cluster->document_ids as $i => $idx) {
									
						$updates = array();
						$updates['gridimage_id'] = $images[$idx]['gridimage_id'];
						$updates['portal_id'] = $id;
						$updates['label'] = $cluster->label;
						$updates['score'] = $cluster->score;
						$updates['sort_order'] = $i;
						
						$sql= updates_to_insert('gridimage_group',$updates);

						queryExecute($sql);
						$count++;
					}
					
				}
			
			}
			
			
		}
		
		print "FINISHED $id with $count labels<BR>\n";
		queryExecute("UPDATE portal SET last_grouped = NOW(),updated=updated WHERE portal_id = $id");
		exit;
	}

}

print "<hr>done\n";
